import os
import re

def merge_homework_to_notes(directory="."):
    # 匹配文件名模式：20251010作业.md
    homework_pattern = re.compile(r"(\d{8})作业\.md")

    for filename in os.listdir(directory):
        match = homework_pattern.match(filename)
        if not match:
            continue

        date = match.group(1)
        homework_file = os.path.join(directory, filename)
        notes_file = os.path.join(directory, f"{date}笔记.md")

        if not os.path.exists(notes_file):
            print(f"⚠️ 未找到对应的笔记文件：{notes_file}，跳过。")
            continue

        with open(homework_file, "r", encoding="utf-8") as hw:
            homework_content = hw.read().strip()

        if not homework_content:
            print(f"⚠️ 作业文件为空：{homework_file}，跳过。")
            continue

        # 加上标题
        merged_content = "\n\n## 作业\n" + homework_content + "\n"

        # 合并到笔记.md 末尾
        with open(notes_file, "a", encoding="utf-8") as notes:
            notes.write(merged_content)

        print(f"✅ 已合并 {filename} → {date}笔记.md")

if __name__ == "__main__":
    merge_homework_to_notes(".")
